<?php

namespace plugin\admin\app\controller;

use Exception;
use plugin\admin\app\model\TaskLog;
use support\Request;
use support\Response;
use plugin\admin\app\model\Order;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;
use think\facade\Cache;

/**
 * 订单 
 */
class OrderController extends Crud
{
    
    /**
     * @var Order
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Order;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('order/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('order/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('order/update');
    }

    /**
     * @throws Exception
     * 获取客户的订单
     */
    public static function getOrder($adminInfo): array
    {
        $orderInfo = Cache::get('orderInfo_'.$adminInfo['company_id']);
        if($orderInfo && self::isToday($orderInfo['time'])) {
            $data = $orderInfo;
        } else {
            $today_consume_num = TaskLog::where([
                'company_id'     => admin('company_id'),
                'consume_status' => 1, // 1是消费了，0是未消费
            ])->whereDate('created_at', date('Y-m-d', time()))->count();
            $data = [
                'today' => $today_consume_num,
                'time' => date('Y-m-d', time())
            ];
            Cache::set('orderInfo_'.$adminInfo['company_id'], $data);
        }
        return $data;
    }

    public static function isToday($timestamp): bool
    {
        // 获取当前日期的开始时间和结束时间
        $startOfDay = strtotime("today");
        $endOfDay = strtotime("tomorrow") - 1;
        // 检查时间戳是否在今天范围内
        return ($timestamp >= $startOfDay && $timestamp <= $endOfDay);
    }

    public static function uploadCode($code = '')
    {
        $codeArr = [
            '1000' => '上传成功',
            '1010' => '解析成功',
            '1011' => '无效链接',
            '1012' => '解析失败',
            //'1013' => '余额不足，请充值',
            //'1014' => '未知错误',
            '1020' => '上传成功',
            '1021' => '到家已存在',
            '1022' => '上传失败'
        ];
        if($code == '') {
            return $codeArr;
        } else {
            return $codeArr[$code];
        }
    }
}
